class Sales::CustomProductsController < Sales::BaseController
  before_action :set_store, :set_normal_store_id, :set_store_id
  before_action :set_custom_product, only: [:show, :edit, :update]
  def new
    @product = StoreProduct.new
  end

  def create
    @status = CustomProductService.call(current_cart, @store, store_product_params, cart_item_params)
    if @status.success?
      redirect_to successful_sales_custom_product_path(@status.obj_id, cart_item_id: @status.obj.id, store_id: @normal_store_id)
    else
      redirect_to new_sales_custom_product_path(store_id: @normal_store_id), notice: @status.notice
    end
  end

  def successful
    @cart_item = CartItem.find(params[:cart_item_id])
  end

  def index
    set_search_params
    @q = @store.products.useable.customs.by_user(current_customer.id).ransack(params[:q])
    @products = @q.result.order("id desc")
  end

  def show

  end

  def edit

  end

  def update
    status = ImageService.call(update_product_params[:images_attributes], @product, type: 'update')
    if status.success?
      @product.update!(update_product_params.except(:images_attributes))
    end
    redirect_to sales_custom_products_path(store_id: @normal_store_id)
  end

  private
  def store_product_params
    params[:store_product][:price] = 1
    params[:store_product][:customable] = true
    params[:store_product][:store_customer_id] = current_customer.id
    params.require(:store_product).permit(
                                      :name,
                                      :price,
                                      :format,
                                      :customable,
                                      :store_customer_id,
                                      images_attributes: [
                                        :image
                                      ]
                                    )
  end

  def cart_item_params
    params[:cart_id] = current_cart.id
    params[:store_id] = @store.id
    # params[:store_product_id] = @product.id
    params.permit(:store_id, :quantity, :store_product_id, :cart_id)
  end

  def set_cart
    @cart = current_cart
  end

  def set_search_params
    params[:q] ||= {}
    @name = params[:q][:name_cont]
  end

  def set_custom_product
    @product = StoreProduct.find(params[:id])
  end

  def update_product_params
    params.require(:store_product).permit(
                                      :name,
                                      :price,
                                      :format,
                                      images_attributes: [
                                        :image
                                      ]
                                    )
  end

end
